package net.alche.sdd.pojo;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.net.multipart.MultipartRequestInputStream;
import cn.hutool.core.net.multipart.UploadFileHeader;
import net.alche.al.util.AC;

public class MultipartFile {
  public static final Logger logger = LoggerFactory.getLogger(MultipartFile.class);
  String fileName = "";
  byte[] byts = null;

  public MultipartFile(org.smartboot.http.server.HttpRequest request) {
    try {
      MultipartRequestInputStream mrs = new MultipartRequestInputStream(request.getInputStream());
      UploadFileHeader uh = mrs.readDataHeader(AC.file.getUtf8());
      if (uh != null) {
        fileName = uh.getFileName();
        byts = mrs.readAllBytes();
      }
    } catch (IORuntimeException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public MultipartFile(HttpServletRequest request) {
    try {
      MultipartRequestInputStream mrs = new MultipartRequestInputStream(request.getInputStream());
      UploadFileHeader uh = mrs.readDataHeader(AC.file.getUtf8());
      if (uh != null) {
        fileName = uh.getFileName();
        byts = mrs.readAllBytes();
      }
    } catch (IORuntimeException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // try {
    // Collection<Part> parts = request.getParts();
    // if (parts != null && !parts.isEmpty()) {
    // logger.info("multipart-file.size = {}", parts.size());
    // for (Part part : parts) {
    // this.byts = part.getInputStream().readAllBytes();
    // this.fileName = part.getName();
    // }
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // } catch (ServletException e) {
    // e.printStackTrace();
    // }
  }

  public boolean isEmpty() {
    return AC.empty(fileName);
  }

  public int getSize() {
    if (byts == null)
      return 0;
    return byts.length;
  }

  public String getOriginalFilename() {
    return fileName;
  }

  public boolean transferTo(String path) {
    FileUtil.writeBytes(byts, path);
    return true;
  }
  public byte[] getByteArrs(){
    return byts;
  }

  public MultipartFile() {

  }
}
